package com.xuecheng.manage_course.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.domain.cms.response.CmsPostPageResult;
import com.xuecheng.framework.domain.course.*;
import com.xuecheng.framework.domain.course.ext.CategoryNode;
import com.xuecheng.framework.domain.course.ext.CourseInfo;
import com.xuecheng.framework.domain.course.ext.CourseView;
import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.framework.domain.course.request.CourseListRequest;
import com.xuecheng.framework.domain.course.response.CoursePublishResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_course.client.CmsPageClient;
import com.xuecheng.manage_course.dao.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CourseService {

    @Autowired
    private TeachplanMapper teachplanMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private TeachplanRepository teachplanRepository;
    @Autowired
    private CourseBaseRepository courseBaseRepository;
    @Autowired
    private CourseMarketRepository courseMarketRepository;
    @Autowired
    private CoursePicRepository coursePicRepository;
    @Autowired
    CmsPageClient cmsPageClient;
    @Autowired
    private CoursePubRepository coursePubRepository;
    @Autowired
    private TeachplanMediaRepository teachplanMediaRepository;
    @Autowired
    private TeachplanMediaPubRepository teachplanMediaPubRepository;

    @Value("${course-publish.dataUrlPre}")
    private String publish_dataUrlPre;
    @Value("${course-publish.pagePhysicalPath}")
    private String publish_page_physicalpath;
    @Value("${course-publish.pageWebPath}")
    private String publish_page_webpath;
    @Value("${course-publish.siteId}")
    private String publish_siteId;
    @Value("${course-publish.templateId}")
    private String publish_templateId;
    @Value("${course-publish.previewUrl}")
    private String previewUrl;



    //根据课程id查询课程
    public TeachplanNode selectList(String courseId){
        TeachplanNode teachplanNode = teachplanMapper.selectList(courseId);
        return teachplanNode;
    }
    //添加课程计划
    @Transactional
    public ResponseResult addTeachplan(Teachplan teachplan) {
        //判断提交数据是否为空
        if(teachplan==null ||
                StringUtils.isEmpty(teachplan.getCourseid())||
                StringUtils.isEmpty(teachplan.getPname())){
            ExceptionCast.cast(CommonCode.INVALIDPARAM);
        }
        //获取课程id
        String courseid = teachplan.getCourseid();
        //获取新添加课程的跟节点ID
        String parentid = teachplan.getParentid();
        //判断跟节点是否 为空
        if(StringUtils.isEmpty(parentid)){
            //取出该课程的根节点
          parentid = this.getTeachplanRoot(courseid);
        }
        //新节点
        Teachplan teachplan1 = new Teachplan();
        //将页面提交的信息拷贝到新节点对象中
        BeanUtils.copyProperties(teachplan,teachplan1);
        teachplan1.setParentid(parentid);
        teachplan1.setCourseid(courseid);
        //设置级别
        //根据父节点id获取父节点
        Optional<Teachplan> optional = teachplanRepository.findById(parentid);
        Teachplan teachplan2 = optional.get();
        //父节点的级别
        String grade = teachplan2.getGrade();
        if(grade.equals("1")){
            teachplan1.setGrade("2");
        }else {
            teachplan1.setGrade("3");
        }
        //保存新的结点
        teachplanRepository.save(teachplan1);

        return new ResponseResult(CommonCode.SUCCESS);
    }
    // 查询课程的根节点，如果查询不到 要自动添加根节点
    public String getTeachplanRoot(String courseId){
        //根据课程id查询课程
        Optional<CourseBase> optional = courseBaseRepository.findById(courseId);
        if(!optional.isPresent()){
            return null;
        }
        CourseBase courseBase = optional.get();
        List<Teachplan> teachplans = teachplanRepository.findByCourseidAndParentid(courseId, "0");
        if(teachplans==null||teachplans.size()<=0){
            //说明没有根节点,要自动添加根节点
            Teachplan teachplan = new Teachplan();
            teachplan.setParentid("0");
            teachplan.setGrade("1");
            teachplan.setPname(courseBase.getName());
            teachplan.setCourseid(courseId);
            teachplan.setStatus("0");
            teachplanRepository.save(teachplan);
            return teachplan.getId();
        }
        //返回根节点id
        return teachplans.get(0).getId();
    }

    //查询所有课程
    public QueryResponseResult<CourseInfo> findCourseList(String companyId,int page, int size,CourseListRequest courseListRequest){
      if(courseListRequest==null){
          courseListRequest=new CourseListRequest();
      }
      courseListRequest.setCompanyId(companyId);
        PageHelper.startPage(page, size);
        Page<CourseInfo> courseList = courseMapper.findCourseListPage(courseListRequest);
        QueryResult<CourseInfo> queryResult = new QueryResult<>();
        queryResult.setList(courseList.getResult());
        queryResult.setTotal(courseList.getTotal());
       return new QueryResponseResult<>(CommonCode.SUCCESS,queryResult);
    }
    //查询课程分类
    public CategoryNode findCourse(){
        CategoryNode course = courseMapper.findCourse();
        return course;
    }
    //添加课程
    @Transactional
    public ResponseResult addCourse(CourseBase courseBase) {
        courseBase.setStatus("202001");
        CourseBase base = courseBaseRepository.save(courseBase);
        if(base!=null){
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return null;
    }
    //根据课程id查询课程信息
    public CourseBase findCourseById(String courseId) {
        Optional<CourseBase> optional = courseBaseRepository.findById(courseId);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }
    //更新课程
    @Transactional
    public ResponseResult updateCoursebase(String courseId, CourseBase courseBase) {
        CourseBase course = this.findCourseById(courseId);
        if(course!=null){
            course.setName(courseBase.getName());
            course.setUsers(courseBase.getUsers());
            course.setMt(courseBase.getMt());
            course.setGrade(courseBase.getGrade());
            course.setStudymodel(courseBase.getStudymodel());
            course.setTeachmode(courseBase.getTeachmode());
            course.setDescription(courseBase.getDescription());
            course.setSt(courseBase.getSt());
            course.setStatus(courseBase.getStatus());
            course.setCompanyId(courseBase.getCompanyId());
            course.setUserId(courseBase.getUserId());
            CourseBase courseBase1 = courseBaseRepository.save(course);
            if(courseBase1!=null){
                return new ResponseResult(CommonCode.SUCCESS);
            }

        }

        return new ResponseResult(CommonCode.FAIL);
    }
    //根据课程id查询课程营销信息
    public CourseMarket getCourseMarketById(String courseId) {
        Optional<CourseMarket> optional = courseMarketRepository.findById(courseId);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }
    //更新营销信息
    @Transactional
    public ResponseResult updateCourseMarket(String courseId, CourseMarket courseMarket) {
        CourseMarket courseMarket1 = getCourseMarketById(courseId);
        if(courseMarket1!=null){
            courseMarket1.setCharge(courseMarket.getCharge());
            courseMarket1.setEndTime(courseMarket.getEndTime());
            courseMarket1.setPrice(courseMarket.getPrice());
            courseMarket1.setValid(courseMarket.getValid());
            courseMarket1.setStartTime(courseMarket.getStartTime());
            courseMarket1.setQq(courseMarket.getQq());
            courseMarket1.setPrice_old(courseMarket.getPrice_old());
            courseMarket1.setExpires(courseMarket.getExpires());
            CourseMarket save = courseMarketRepository.save(courseMarket1);
            if(save!=null){
                return new ResponseResult(CommonCode.SUCCESS);
            }
        }
        CourseMarket market = courseMarketRepository.save(courseMarket);
        if(market==null){
            return new ResponseResult(CommonCode.FAIL);
        }
        return  new ResponseResult(CommonCode.SUCCESS);
    }
    //获取课程图片
    public CoursePic findCoursePic(String courseId) {

        CoursePic coursePic = courseMapper.findCoursePic(courseId);
        if(coursePic!=null){
            return coursePic;
        }
        return null;

    }
    //保存课程图片
    @Transactional
    public ResponseResult addCoursePic(String courseId, String pic) {
        Optional<CoursePic> optional = coursePicRepository.findById(courseId);
        CoursePic coursePic=null;
        if(optional.isPresent()){
            coursePic=optional.get();
        }
        if(coursePic==null){
            coursePic=new CoursePic();
        }
        coursePic.setCourseid(courseId);
        coursePic.setPic(pic);
        coursePicRepository.save(coursePic);
        return new ResponseResult(CommonCode.SUCCESS);
    }
    //删除课程图片
    @Transactional
    public ResponseResult deleteCoursePic(String courseId) {
        Long size = coursePicRepository.deleteByCourseid(courseId);
        if(size>0){
           return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.FAIL);
    }
    //获取课程页面信息
    public CourseView getCoruseView(String id) {
        CourseView courseView = new CourseView();
        //查询课程信息
        CourseBase courseBase = this.findCourseById(id);
            courseView.setCourseBase(courseBase);
        //查询课程营销信息
        CourseMarket courseMarket = this.getCourseMarketById(id);
        courseView.setCourseMarket(courseMarket);
        //查询图片信息
        CoursePic coursePic = this.findCoursePic(id);
        courseView.setCoursePic(coursePic);
        //查询课程计划
        TeachplanNode teachplanNode = this.selectList(id);
        courseView.setTeachplanNode(teachplanNode);
        return courseView;
    }
    //预览课程
    public CoursePublishResult preview(String id) {
        CourseBase course = this.findCourseById(id);
        //请求cms添加页面
        //准备cms信息
        CmsPage cmsPage = new CmsPage();
        cmsPage.setSiteId(publish_siteId);//站点id
        cmsPage.setDataUrl(publish_dataUrlPre+id);//数据模型url
        cmsPage.setPageName(id+".html");//页面名称
        cmsPage.setPageAliase(course.getName());//页面别名，就是课程名称
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);//页面物理路径
        cmsPage.setPageWebPath(publish_page_webpath);//页面webpath
        cmsPage.setTemplateId(publish_templateId);//页面模板id
        //远程调用cms
        CmsPageResult cmsPageResult = cmsPageClient.save(cmsPage);
        if(!cmsPageResult.isSuccess()){
            //不成功
            return  new CoursePublishResult(CommonCode.FAIL,null);
        }
        //成功的话拿到页面信息
        CmsPage cmsPage1 = cmsPageResult.getCmsPage();
        String pageId = cmsPage1.getPageId();
        //拼装页面预览得url
        String url=previewUrl+pageId;

        //返回CoursePublishResult对象
        return new CoursePublishResult(CommonCode.SUCCESS,url);
    }
    //课程发布
    @Transactional
    public CoursePublishResult publish(String id) {
        //调用cms一键发布接口将页面详情发布到服务器
        //获取课程信息
        CourseBase courseBase = this.findCourseById(id);
        //准备cms信息
        CmsPage cmsPage = new CmsPage();
        cmsPage.setSiteId(publish_siteId);//站点id
        cmsPage.setDataUrl(publish_dataUrlPre+id);//数据模型url
        cmsPage.setPageName(id+".html");//页面名称
        cmsPage.setPageAliase(courseBase.getName());//页面别名，就是课程名称
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);//页面物理路径
        cmsPage.setPageWebPath(publish_page_webpath);//页面webpath
        cmsPage.setTemplateId(publish_templateId);//页面模板id

        CmsPostPageResult cmsPostPageResult = cmsPageClient.postPageQuick(cmsPage);
        if(!cmsPostPageResult.isSuccess()){
            return new CoursePublishResult(CommonCode.FAIL,null);
        }
        //更改课程发布状态
        CourseBase courseBase1 = this.saveCoursePubState(id);
        //获得页面的url
        String pageUrl = cmsPostPageResult.getPageUrl();

        //发布课程详情页面
        //创建coursePub对象
        CoursePub coursePub = this.getCoursePub(id);
        //将coursePub对象保存到数据库
        this.saveCoursePub(id,coursePub);
        //保存课程索引信息
        saveTeachplanMediaPub(id);
        //缓存课程的信息
        return new CoursePublishResult(CommonCode.SUCCESS,pageUrl);
    }
    //根据课程Id保存媒资信息
    public void saveTeachplanMediaPub(String courseId){
        //根据课程id删除媒资信息
        Optional<TeachplanMediaPub> optional = teachplanMediaPubRepository.findById(courseId);
        if(optional.isPresent()) {
            teachplanMediaPubRepository.deleteByCourseId(courseId);
        }
        //根据课程id查询媒资信息
        List<TeachplanMedia> mediaList = teachplanMediaRepository.findByCourseId(courseId);
        for (TeachplanMedia teachplanMedia : mediaList) {
            TeachplanMediaPub teachplanMediaPub = new TeachplanMediaPub();
            BeanUtils.copyProperties(teachplanMedia,teachplanMediaPub);
            teachplanMediaPub.setTimestamp(new Date());
            teachplanMediaPubRepository.save(teachplanMediaPub);
        }
    }
    //将CoursePub保存到数据库
    public CoursePub saveCoursePub(String id,CoursePub coursePub){
        Optional<CoursePub> optional = coursePubRepository.findById(id);
        CoursePub coursePubNew = null;
        if(optional.isPresent()){
            coursePubNew=optional.get();
        }else {
            coursePubNew=new CoursePub();
        }
        BeanUtils.copyProperties(coursePub,coursePubNew);
        coursePubNew.setId(id);
        //设置时间戳
        coursePubNew.setTimestamp(new Date());
        //设置发布时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        coursePubNew.setPubTime(simpleDateFormat.format(new Date()));
        coursePubRepository.save(coursePubNew);
        return coursePubNew;
    }
    //创建CoursePub对象
    public CoursePub getCoursePub(String id){
        //创建CoursePub对象
        CoursePub coursePub = new CoursePub();
        //查询课程基本信息
        Optional<CourseBase> baseOptional = courseBaseRepository.findById(id);
        if(baseOptional.isPresent()){
            CourseBase courseBase = baseOptional.get();
            BeanUtils.copyProperties(courseBase,coursePub);
        }
        //根据Id查询课程图片信息
        Optional<CoursePic> picOptional = coursePicRepository.findById(id);
        if(picOptional.isPresent()){
            CoursePic coursePic = picOptional.get();
            BeanUtils.copyProperties(coursePic,coursePub);
        }
        //根据id查询课程营销信息
        Optional<CourseMarket> marketOptional = courseMarketRepository.findById(id);
        if(marketOptional.isPresent()){
            CourseMarket courseMarket = marketOptional.get();
            BeanUtils.copyProperties(courseMarket,coursePub);
        }
        //根据Id查询课程计划
        TeachplanNode teachplanNode = teachplanMapper.selectList(id);
        //将课程计划转换成json字符串
        String teachplanString = JSON.toJSONString(teachplanNode);
        coursePub.setTeachplan(teachplanString);

        return coursePub;
    }

    //更改课程状态
    public CourseBase saveCoursePubState(String pageId){
        CourseBase courseBase = this.findCourseById(pageId);
        courseBase.setStatus("202002");
        CourseBase save = courseBaseRepository.save(courseBase);
        return save;
    }

      //保存媒资信息
    public ResponseResult savemedia(TeachplanMedia teachplanMedia) {
        if(teachplanMedia==null){
            ExceptionCast.cast(CommonCode.INVALIDPARAM);
        }
        //获取课程计划id
        String teachplanId = teachplanMedia.getTeachplanId();
        //查询课程计划
        Optional<Teachplan> optional1 = teachplanRepository.findById(teachplanId);
        if(!optional1.isPresent()){
            ExceptionCast.cast(CommonCode.INVALIDPARAM);
        }
        Teachplan teachplan = optional1.get();
        //只允许为子结点课程计划选择视频
        String grade = teachplan.getGrade();
        if(StringUtils.isEmpty(grade)||! grade.equals("3")){
            ExceptionCast.cast(CommonCode.FAIL);
        }
        Optional<TeachplanMedia> optional = teachplanMediaRepository.findById(teachplanId);
        TeachplanMedia one=null;
        if(optional.isPresent()){
            one=optional.get();
        }else {
            one=new TeachplanMedia();
        }
        one.setTeachplanId(teachplanId);
        one.setMediaFileOriginalName(teachplanMedia.getMediaFileOriginalName());
        one.setCourseId(teachplanMedia.getCourseId());
        one.setMediaId(teachplanMedia.getMediaId());
        one.setMediaUrl(teachplanMedia.getMediaUrl());
        teachplanMediaRepository.save(one);
        return new ResponseResult(CommonCode.SUCCESS);
    }
}
